<?php

namespace app\live\controller;

use app\common\model\live\GoodsModel;
use app\common\model\live\MallModel;
use app\common\model\live\PayModel;
use app\common\model\MemberModel;
use helper\Str;
use wechat\Factory;

class PayController extends BaseController
{

  private $model;
  private $wechatPpay;

  /**
   * 初始化
   */
  public function __construct()
  {
    parent::__construct();
    $this->model = new PayModel();
    $this->wechatPpay = Factory::payment();
  }

  /**
   * 打赏支付
   * @throws \Exception
   */
  public function gift()
  {
    $data = $this->request->param();
    validate([
        'pay_type|支付类型' => 'require|in:1,2',
        'room_id|房间号' => 'require|number',
        'from_user_id|会员' => 'require'
    ], $data);
    if ($data['pay_type'] == 1) { //红包打赏
      $totalFee  = $this->request->param('total_fee/f');
      $orderName = "红包{$totalFee}元";
      $attach =  "{$data['pay_type']}|{$data['room_id']}|{$data['from_user_id']}|{$orderName}";
    } else { //礼物打赏,价格后台计算
      $giftId    = $this->request->param('gift_id/d'); //礼物ID
      $giftNum   = $this->request->param('gift_num/d'); //礼物数量
      $gift      = D('live.Gift')->where('id', $giftId)->find();
      $orderName = "赠送[{$gift['name']}]×{$giftNum}";
      $totalFee  = $gift['price'] * $giftNum;
      if($totalFee==0){
        $this->success('免费礼物');
      }
      $attach =  "{$data['pay_type']}|{$data['room_id']}|{$data['from_user_id']}|{$orderName}";
    }
    $member = MemberModel::where('id', $data['from_user_id'])->find(); //会员
    $orderInfo = [
        'body' => $orderName,
        'out_trade_no' => Str::builderOrderSn(),
        'total_fee' => $totalFee * 100,
        'notify_url' => 'https://wechat.180wx.cn/live/pay/notify.html',
        'trade_type' => 'JSAPI',
        'openid' => $member['openid'],
        'attach'=> $attach
    ];
    $result = $this->wechatPpay->order->unify($orderInfo);
    $json   = $this->wechatPpay->jssdk->bridgeConfig($result['prepay_id']);
    $this->success('操作成功', null, $json);
  }

  /*直播商品购买*/
  public function order(){
    $data = $this->request->param();
    $this->validate($data, [
        'address_info|收货地址' => 'require',
        'goods_id|商品' => 'require|number',
        'goods_num|购买数量' => 'require|number',
        'from_user_id|会员' => 'require'
    ]);
    $data['address_info'] = html_out($data['address_info']);
    $goodsInfo = GoodsModel::where('id',$data['goods_id'])->find();
    if(empty($goodsInfo)) abort(500,'商品信息不存在');
    if($goodsInfo['is_sale']==0) abort(500,'商品已售罄');
    if($goodsInfo['is_sale']==-1) abort(500,'商品已下架');
    if($data['goods_num']>$goodsInfo['goods_stock']) abort(500,'商品库存不足');
    $orderName = $goodsInfo['title'];
    $totalFee = $goodsInfo['sale_price']*$data['goods_num'];
    $attach =  "3|{$goodsInfo['room_id']}|{$data['from_user_id']}}";
    $member = MemberModel::where('id', $data['from_user_id'])->find(); //会员
    $orderSn = Str::builderOrderSn();
    $orderInfo = $this->model->where('from_user_id',$data['from_user_id'])->where('goods_id',$data['goods_id'])->where('is_pay',0)->where('is_fail',0)->find();
    /*没有相同未支付订单创建订单，有未支付的相同订单，更新订单*/
    if(empty($orderInfo)){
      $data = [
          'pay_type'=>3,
          'order_sn'=>$orderSn,
          'order_name'=>$orderName,
          'room_id'=>$goodsInfo['room_id'],
          'from_user_id'=>$data['from_user_id'],
          'from_name'=>$member['nick'],
          'total_fee'=>$totalFee,
          'address_info'=>$data['address_info'],
          'goods_id'=>$data['goods_id'],
          'goods_num'=>$data['goods_num'],
          'goods_info'=>json_encode($goodsInfo),
      ];
      $info = $this->model->add($data);
    }else{
      $data = [
          'order_sn'=>$orderSn,
          'from_name'=>$member['nick'],
          'total_fee'=>$totalFee,
          'address_info'=>$data['address_info'],
          'goods_id'=>$data['goods_id'],
          'goods_num'=>$data['goods_num'],
          'goods_info'=>json_encode($goodsInfo),
      ];
      $info = $this->model->where('id',$orderInfo['id'])->update($data);
    }
    $failTime = MallModel::where('room_id',$goodsInfo['room_id'])->value('fail_time');
    $failTime = empty($failTime)?1800:$failTime*60;
    queue('app\common\job\Order@changePay', "{\"order_sn\":\"{$orderSn}\"}",$failTime);
    /*减库存,判断售罄*/
    GoodsModel::where('id',$data['goods_id'])->dec('goods_stock',(int)$data['goods_num'])->update();
    $goods_stock = GoodsModel::where('id',$data['goods_id'])->value('goods_stock');
    if($goods_stock<=0){
      GoodsModel::where('id',$data['goods_id'])->update(['is_sale'=>0]);
    }
    $orderInfo = [
        'body' => $orderName,
        'out_trade_no' => $orderSn,
        'total_fee' => $totalFee * 100,
        'notify_url' => 'https://wechat.180wx.cn/live/pay/notify.html',
        'trade_type' => 'JSAPI',
        'openid' => $member['openid'],
        'attach'=> $attach
    ];
    $result = $this->wechatPpay->order->unify($orderInfo);
    $json   = $this->wechatPpay->jssdk->bridgeConfig($result['prepay_id']);
    $this->success('操作成功', null, $json);

  }

  /**
   * 支付回调
   */
  public function notify()
  {
    $response = $this->wechatPpay->handlePaidNotify(function ($message, $fail) {
      if ($message['return_code'] === 'SUCCESS' && $message['result_code']=== 'SUCCESS') {
        $payModel = new PayModel();
        $payModel->pay($message);
        return true; // 返回处理完成
      } else {
        return $fail('通信失败，请稍后再通知我');
      }
    });
    return $response; // return $response;
  }

}